﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace FS2
{
	class Program
	{
		static String ROOT = "C:\\Games\\FreeSpace2\\Root_fs2.vp";
		static int WEAPON_START = 0x1B0C9B;
		static int WEAPON_END = 0x1EFD40;
		static int WEAPON_SIZE = WEAPON_END - WEAPON_START;
		static void Main(string[] args)
		{
			ConsoleKey X = ConsoleKey.Zoom;
			while (X != ConsoleKey.X)
			{
				X = Console.ReadKey(true).Key;
				switch (X)
				{
					case ConsoleKey.L:
						ExtractWeapons();
						break;
					case ConsoleKey.S:
						PatchWeapons();
						break;
					default:
						Console.WriteLine("--Invalid Key--");
						break;
				}
			}
		}
		static void Extract(String FN, String Trg, int I, int Cnt)
		{
			BinaryReader R = new BinaryReader(File.OpenRead(FN));
			R.BaseStream.Seek(I, SeekOrigin.Begin);
			File.WriteAllBytes(Trg, R.ReadBytes(Cnt));
			R.Close();
			GC.Collect();
			Console.WriteLine(Cnt + " bytes extracted to \"" + Trg + "\"");
		}
		static void Patch(String FN, String Src, int I, int Cnt)
		{
			FileInfo FI = new FileInfo(Src);
			if (FI.Length != Cnt)
			{
				Console.WriteLine("File size: " + FI.Length.ToString().PadRight(9) + " needed " + Cnt.ToString().PadLeft(9) + " diff: " + (FI.Length - Cnt).ToString());
				return;
			}
			BinaryWriter W = new BinaryWriter(File.OpenWrite(FN));
			W.BaseStream.Seek(I, SeekOrigin.Begin);
			W.Write(File.ReadAllBytes(Src));
			W.Close();
			Console.WriteLine("\"" + FN + "\" Patched");
			GC.Collect();
		}
		static void ExtractWeapons()
		{
			Extract(ROOT, "weapons.txt", WEAPON_START, WEAPON_SIZE);
		}
		static void PatchWeapons()
		{
			Patch(ROOT, "weapons.txt", WEAPON_START, WEAPON_SIZE);
		}
	}
}
